﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Linq;

namespace SkypeBot.Core
{
    public class RSSParser
    {
        public static IEnumerable<Channel> GetChannelQuery(XDocument xdoc)
        {
            return from channels in xdoc.Descendants("channel")
                   select new Channel
                   {
                       Title = channels.Element("title") != null ? channels.Element("title").Value : string.Empty, 
                       Link = channels.Element("link") != null ? channels.Element("link").Value : string.Empty, 
                       Description = channels.Element("description") != null ? channels.Element("description").Value : string.Empty, 
                       Items = from items in channels.Descendants("item")
                               select new Item
                               {
                                   Title = items.Element("title") != null ? items.Element("title").Value : string.Empty, 
                                   Link = items.Element("link") != null ? items.Element("link").Value : string.Empty, 
                                   Description = items.Element("description") != null ? items.Element("description").Value : string.Empty, 
                                   Guid = items.Element("guid") != null ? items.Element("guid").Value : string.Empty
                               }
                   };
        }

        public static IList<Item> GetRecords(string strURI, Encoding enc)
        {
            IList<Item> mobjList = new List<Item>();

            if (!string.IsNullOrEmpty(strURI))
            {
                var mobjChannels = GetChannelQuery(XDocument.Load(new StreamReader(HttpWebRequest.Create(strURI).GetResponse().GetResponseStream(), enc)));

                foreach (var channel in mobjChannels)
                {
                    foreach (var item in channel.Items)
                    {
                        mobjList.Add(item);
                    }
                }
            }

            return mobjList;
        }

        public static IList<Item> GetRecords(string strURI)
        {
            return GetRecords(strURI, Encoding.Default);
        }
    }

    public class Channel
    {
        public string Title { get; set; }
        public string Link { get; set; }
        public string Description { get; set; }
        public IEnumerable<Item> Items { get; set; }
    }

    public class Item
    {
        public string Title { get; set; }
        public string Link { get; set; }
        public string Description { get; set; }
        public string Guid { get; set; }
    }
}
